﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using BaseControlLibrary;
using CommonControlLibrary;
using CommonControlLibrary.Common;
using DBAccessLibrary.Model;
using DevExpress.Xpf.Docking;
using DevControlLibrary.UI;
using DevControlLibrary.ViewModel;
using DevExpress.Xpf.Bars;
using DevExpress.Xpf.Ribbon;
using DevExpress.Utils;
using DevControlLibrary.Common;
using QueryResource.Common;
using QueryResource.ViewModel;
using DevExpress.Xpf.Core;
using DevControlLibrary.UI.Comparsion;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Linq;
using DBAccessLibrary;

namespace DevControlLibrary
{
    /// <summary>
    /// RibbonMainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class RibbonMainWindow : DXWindow
    {
        public RibbonMainWindow(ISplash sp)
        {
            sp.SetProgress(50, "正在加载控件……");
            InitializeComponent();

            WindowHelper.FlushMemory(this);
            this.Closed += MainWindow_Closed;
            this.dockManager.DockItemClosing += new DevExpress.Xpf.Docking.Base.DockItemCancelEventHandler(dockManager_DockItemClosing);

            sp.SetProgress(80, "正在初始化数据……");
            Init();
            sp.SetProgress(100, "加载完成……");
            sp.CloseSplash();

        }

       


        //主界面
        public MainViewModel ViewModel { get; set; }
        //树
        public DBTreeViewModel TreeViewModel { get; set; }
        //数据对比
        public DataComparsionViewModel ComparsionViewModel { get; set; }

        public BitmapImage GetImageSource(string itemPath)
        {
            BitmapImage img = new BitmapImage();
            img.BeginInit();

            img.CacheOption = BitmapCacheOption.OnLoad;
            img.UriSource = new Uri(String.Format("pack://application:,,,/{0};component/{1}", System.Reflection.Assembly.GetExecutingAssembly().FullName, itemPath));
            img.EndInit();
            img.Freeze();
            return img;
        }

        #region 事件
        private void dockManager_DockItemClosed(object sender, DevExpress.Xpf.Docking.Base.DockItemClosedEventArgs e)
        {
            LayoutPanel panel = e.Item as LayoutPanel;
            if (e.Item is LayoutGroup)
            {
                panel = (e.Item as LayoutGroup).Items[0] as LayoutPanel;
            }
            if (panel != null)
            {
                if(panel.Content is GridViewControl)
                {
                    GridViewControl control = panel.Content as GridViewControl;
                    control.Dispose();
                }
                else if (panel.Content is TableDefinitionControl)
                {
                    TableDefinitionControl control = panel.Content as TableDefinitionControl;
                    control.WriteLog = null;
                }
            }
        }
        void dockManager_DockItemClosing(object sender, DevExpress.Xpf.Docking.Base.ItemCancelEventArgs e)
        {
             LayoutPanel panel = e.Item as LayoutPanel;
            if (e.Item is LayoutGroup)
            {
                panel = (e.Item as LayoutGroup).Items[0] as LayoutPanel;
            }
            if (panel != null)
            {
                if (panel.Content is TableDefinitionControl)
                {
                    TableDefinitionControl control = panel.Content as TableDefinitionControl;
                    if (panel.Caption.ToString().IndexOf('*') > 0)
                    {
                        string tablename = panel.Caption.ToString().Replace("*", "");
                        if (MessageBoxHelper.ShowMessage(string.Format("是否要保存表{0}的修改", tablename),
                                                  "保存",
                                                  MessageBoxButton.OKCancel,
                                                  MessageBoxImage.Information) == MessageBoxResult.OK)
                        {
                            if (!control.Save())
                                MessageBoxHelper.Show("保存失败");
                        }
                        else
                        {
                            control.RollBack();
                        }
                    }
                }
                else if (panel.Content is SQLControl)
                {
                    SQLControl sql = panel.Content as SQLControl;
                    if (sql != null)
                    {
                        sql.Dispose();
                    }
                }
            }
           
        }
      
        void MainWindow_Closed(object sender, EventArgs e)
        {
            if (!isUpdate)
            {
                SaveDocumentContent();
            }
            //Environment.Exit(0);

            this.dockManager.SaveLayoutToXml(System.AppDomain.CurrentDomain.BaseDirectory +"\\DockLayout.xml");
            XmlHelper.Instance.IsRibbonVisible = this.ribbonControl1.IsMinimized;
            if (Application.Current != null)
            {
                Application.Current.Shutdown(-1);
            }

        }
        public void SaveDocumentContent()
        {
            bool isFirstMsg = false;
            bool isResult = false;
            Func<bool> showMsg = () =>
            {
                if (!isFirstMsg)
                {
                    if (MessageBoxHelper.ShowMessage("是否保存当前所有文档的内容?", "保存", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
                    {
                        isResult = true;
                    }
                    isFirstMsg = true;
                }
                return isResult;
            };
            foreach (LayoutPanel panel in GetAllLayoutPanel())
            {
                if (panel.Content is SQLControl)
                {
                    string fileName = string.Empty;
                    if (panel.Caption.ToString().IndexOf('*') > 0)
                    {
                        SQLControl sql = panel.Content as SQLControl;
                        if (sql.IsNewDocument)
                        {
                            fileName = panel.Caption.ToString().Replace("*", "");
                            if (fileName != "文档")
                            {
                                fileName = "Temporary\\" + fileName;
                            }
                            if (showMsg())
                            {
                                sql.SaveFile(fileName);
                            }
                        }
                        else
                        {
                            //文件
                            if (File.Exists(sql.FilePath))
                            {
                                if (showMsg())
                                {
                                    sql.SaveFile(sql.FilePath);
                                }
                            }
                        }
                    }
                }
            }
        }

        private void dockManager_DockItemActivating(object sender, DevExpress.Xpf.Docking.Base.ItemCancelEventArgs e)
        {
            if (e.Item == newNote)
            {
                ViewModel.AddDocumentCommand.Execute(null);
                e.Cancel = true;
            }
        }

        #endregion

        #region 工具栏
        //皮肤
        protected virtual void OnThemeDropDownGalleryInit(object sender, DropDownGalleryEventArgs e)
        {
            Gallery gallery = e.DropDownGallery.Gallery;
            gallery.AllowHoverImages = false;
            gallery.IsItemCaptionVisible = true;
            gallery.ItemGlyphLocation = Dock.Top;
            gallery.IsGroupCaptionVisible = DefaultBoolean.True;
        }
        protected virtual void OnThemeItemClick(object sender, GalleryItemEventArgs e)
        {
            string themeName = (string)e.Item.Caption;
            themeName = themeName.Replace(" ", string.Empty);
            ViewModel.SkinChanged(this,themeName);
        }
        //新建数据源
        private void CreateDB_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.CreateDBCommand.Execute(null);
        }
        //拷贝字段名
        private void CopyFieldName_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.CopyFieldNameExecuted();
        }
        //格式刷
        private void TxtFormat_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = ViewModel.TxtFormatCanExecute();
        }
        private void TxtFormat_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.TxtFormatExecuted();
        }
        //打开文件
        private void FileOpen_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.FileOpenExecuted();
        }
        //另存为文件
        private void FileSaveAs_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.FileSaveAsExecuted();
        }
        private void FileSaveAs_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = ViewModel.FileSaveAsCanExecute();
        }
        //保存文件
        private void FileSave_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.FileSaveCommand.Execute(null);
        }
        private void FileSave_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = ViewModel.FileSaveCommand.CanExecute(null);
        }
        //运行
        private void RunSQL_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.RunSqlExecuted();
           
        }
        private void RunSQL_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = ViewModel.RunSqlCanExecute();
        }
        //删除数据源
        private void DelDB_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            TreeViewModel.DeleteCommand.Execute(TreeViewModel.SelectedItem);
        }
        private void DelDB_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = TreeViewModel != null && TreeViewModel.DeleteCommand.CanExecute(null);
        }

        //连接
        private void ConnectionDB_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            TreeViewModel.ConnectDBCommand.Execute(TreeViewModel.SelectedItem);
        }
        private void ConnectionDB_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = TreeViewModel != null && TreeViewModel.ConnectDBCommand.CanExecute(null);
        }

        //断开连接
        private void UnConnectionDB_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            TreeViewModel.UnConnectDBCommand.Execute(TreeViewModel.SelectedItem);
        }
        private void UnConnectionDB_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = TreeViewModel != null && TreeViewModel.UnConnectDBCommand.CanExecute(null);
        }

        //清空
        private void TxtClear_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            ViewModel.ClearCommand.Execute(null);
        }
        private void TxtClear_CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = TreeViewModel != null && ViewModel.ClearCommand.CanExecute(null);
        }

        //更新
        bool isUpdate;      //此标志为了 防止关闭窗体时 再次生成数据文件
        private void bUpdate_ItemClick(object sender, ItemClickEventArgs e)
        {
            isUpdate = UpdateHelper.Update(SaveDocumentContent);
            if (isUpdate)
            {
                Application.Current.Shutdown();
            }
        }
        //配置
        private void bSetting_ItemClick(object sender, ItemClickEventArgs e)
        {
            SettingWindow setting = new SettingWindow();
            setting.ShowDialog();
        }
        //注释
        private void Comment_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            LayoutPanel panel = GetSelectedDocumentControl<SQLControl>();
            if (panel != null)
            {
                SQLControl control = panel.Content as SQLControl;
                if (control != null)
                    control.Comment_CommandBinding_Executed(null, null);
            }
        }
        //取消注释
        private void NoComment_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            LayoutPanel panel = GetSelectedDocumentControl<SQLControl>();
             if (panel != null)
             {
                 SQLControl control = panel.Content as SQLControl;
                 if (control != null)
                     control.NoComment_CommandBinding_Excuted(null, null);
             }
        }

        #region 数据对比
        private void ComConnection_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            DataComparsionControl control = ShowDataComparsionWindow("数据对比");

            control.Connection_Click();
            ActionLayoutPanel(documentLog,false);
        }
       
        private void Comparsion_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            LayoutPanel panel = GetDocumentControl<DataComparsionControl>();
            if (panel != null)
            {
                DataComparsionControl ctrl = panel.Content as DataComparsionControl;
                if (ctrl != null && (ctrl.ViewModel.DataSourceList.Count > 0 && !ctrl.ViewModel.IsBusy))
                {
                    e.CanExecute = true;
                }
                else
                {
                    e.CanExecute = false;
                }
            }
            else
            {
                e.CanExecute = false;
            }
        }
        private void ComRefresh_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            LayoutPanel panel = GetDocumentControl<DataComparsionControl>();
            if (panel != null)
            {
                DataComparsionControl control = panel.Content as DataComparsionControl;
                if (control != null) control.Refresh();
            }
        }
        private void ComData_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            LayoutPanel panel = GetDocumentControl<DataComparsionControl>();
            if (panel != null)
            {
                DataComparsionControl control = panel.Content as DataComparsionControl;
                if (control != null) control.Comparsion_Click();
            }
        }
        private void ComSync_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            LayoutPanel panel = GetDocumentControl<DataComparsionControl>();
            if (panel != null)
            {
                DataComparsionControl control = panel.Content as DataComparsionControl;
                if (control != null) control.ViewModel.SyncData();
            }
        }
        private void ComRowCount_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            LayoutPanel panel = GetDocumentControl<DataComparsionControl>();
            if (panel != null)
            {
                DataComparsionControl control = panel.Content as DataComparsionControl;
                if (control != null) control.ViewModel.SyncRowCount();
            }
        }
        private void ComExportoRow_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            LayoutPanel panel = GetDocumentControl<DataComparsionControl>();
            if (panel != null)
            {
                DataComparsionControl control = panel.Content as DataComparsionControl;
                if (control != null) control.ButtonExport_Click();
            }
        }
        private void ComPartExportRow_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            LayoutPanel panel = GetDocumentControl<DataComparsionControl>();
            if (panel != null)
            {
                DataComparsionControl control = panel.Content as DataComparsionControl;
                if (control != null) control.ButtonPartExport_Click();
            }
        }
        private void ComRemoveTable_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            LayoutPanel panel = GetDocumentControl<DataComparsionControl>();
            if (panel != null)
            {
                DataComparsionControl control = panel.Content as DataComparsionControl;
                if (control != null) control.ViewModel.RemoveData();
            }
        }
        private void ComRowContent_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            LayoutPanel panel = GetDocumentControl<DataComparsionControl>();
             if (panel != null)
             {
                 DataComparsionControl control = panel.Content as DataComparsionControl;
                 if (control != null) control.ButtonRowContent_Click();
             }
        }
        #endregion
        #endregion
      

       
        #region 私有函数

        private BaseLayoutItem NewSqlDocument(string caption, string content, bool isNew)
        {
            DocumentPanel panel = new DocumentPanel {
                Caption = caption, 
                AllowRename = false,
                AllowDrag =false,
                AllowDrop =false,
                AllowFloat =false,
                FloatOnDoubleClick =false
            };
            SQLControl control = new SQLControl{
                ViewModel = {
                    AppendLogAction = ShowLog, 
                    AppendDataAction = ShowDS
                }, 
                Tag = panel
            };
          
            panel.Content = control;
            control.ChangeContentAction = SqlControlContentChange;
           
            if (isNew)
            {
                control.Init(false, false);
                control.IsNewDocument = true;
                control.FilePath = caption;
                control.LoadText(content);
              
            }
            else
            {
                control.Init(false);
                control.LoadFile(content);
            }
            if( this.documentSQL.Parent == null)
            {
                throw new Exception("没有地方可以添加新文档");
            }
            
            int index = this.documentSQL.Parent.Items.Count -1;
            this.documentSQL.Parent.Items.Insert(index,panel);
            return panel;
        }
        private void ShowNewWindowLoadFile(string caption, string content,bool isFile)
        {
            BaseLayoutItem item = GetAllLayoutPanel().FirstOrDefault(o => (string)o.Caption == caption);
            if (item != null && item.Parent == null)
            {
                this.dockManager.DockController.RemovePanel(item as LayoutPanel);
                item = null;
            }
            if (item != null)
            {
                if(!isFile)
                {
                    string fileName = Path.GetFileNameWithoutExtension(caption);
                    item = NewSqlDocument(fileName + new Random().Next(5, 9), content, true);
                }
            }
            else
            {
                item = NewSqlDocument(caption, content, !isFile);
            }
            ActionLayoutPanel(item,true);
            SendKeys.Press(Key.Up);
        }
        private void ShowNewConrolToDocument(string caption, DockPanel dp)
        {
            BaseLayoutItem item = GetAllLayoutPanel().FirstOrDefault(o => o.Caption.ToString() == caption);
            if (item != null && item.Parent == null)
            {
                this.dockManager.DockController.RemovePanel(item as LayoutPanel);
                item = null;
            }
            if (item == null)
            {
                DocumentPanel panel = new DocumentPanel {Caption = caption, AllowRename = false};
                dp.Tag = panel;
                panel.Content = dp;

                int index = this.documentSQL.Parent.Items.Count - 1;
                this.documentSQL.Parent.Items.Insert(index, panel);
                item = panel;
            }

            ActionLayoutPanel(item,true);
        }

        /// <summary>
        /// 弹出数据对比窗体（唯一）
        /// </summary>
        /// <param name="caption"></param>
        private DataComparsionControl ShowDataComparsionWindow(string caption)
        {
            LayoutPanel panel = GetDocumentControl<DataComparsionControl>();
            if (panel != null && panel.Parent == null)
            {
                this.dockManager.DockController.RemovePanel(panel as LayoutPanel);
                panel = null;
            }
            if (panel == null)
            {
                panel = new DocumentPanel {Caption = caption};
                DataComparsionControl dc = new DataComparsionControl {ViewModel = {AppendLogAction = ShowLog}};
                panel.Content = dc;
                int index = this.documentSQL.Parent.Items.Count - 1;
                this.documentSQL.Parent.Items.Insert(index, panel);
            }
            ActionLayoutPanel(panel,false);
            return panel.Content as DataComparsionControl;
        }
        private void ShowSQL(string sql, SqlControlStatus status)
        {
            LayoutPanel panel = GetSelectedDocumentControl<SQLControl>();
             if (panel != null)
             {
                 SQLControl control = panel.Content as SQLControl;
                 if (control != null)
                 {
                     control.ViewModel.ExecAppendCmd(sql, status);
                     ActionLayoutPanel(panel,true);
                 }
                 else
                 {
                     this.sqlcontrol.ViewModel.ExecAppendCmd(sql, status);
                 }
             }
        }

        private void ShowLog(string msg, Color errorColor)
        {
            if (errorColor != Colors.Black)
            {
                this.dockManager.InvokeEx(() =>
                {
                    ActionLayoutPanel(documentLog,false);
                });
            }
            this.logcontrol.ScrollToEnd();
            this.logcontrol.WriteLog(msg, errorColor);
            ActionSqlDocument();
        }
        /// <summary>
        /// 激活当前内容窗体
        /// </summary>
        private void ActionSqlDocument()
        {
            this.dockManager.InvokeEx(() =>
            {
                LayoutPanel panel = GetSelectedDocumentControl<SQLControl>();
                if (panel != null)
                {
                    ActionLayoutPanel(panel,true);
                }
            });
          
        }

        private void ShowDS(string sql)
        {
            this.InvokeEx(() =>
            {
                GridViewControl control = GetNoBusyGridControl(true);

                if (control != null)
                {
                    control.DataBind(sql);
                }
                else
                {
                    LayoutGroup group = this.documentDS.Parent;
                    if (@group == null)
                    {
                        GridViewControl gridcontrol = documentDS.Content as GridViewControl;
                        if (gridcontrol != null)
                        {
                            if (gridcontrol.ViewModel.IsBusy)
                            {
                                ShowLog("正在查询中……", Colors.Blue);
                            }
                            else
                            {
                                ActionLayoutPanel(group, false);
                                gridcontrol.DataBind(sql);
                            }
                        }
                    }
                    else
                    {
                        ////新增一个窗体
                        LayoutPanel panel = new LayoutPanel { Caption = "数据" };

                        control = new GridViewControl
                                      {
                                          AppendDataSucess = ShowDataSucess
                                      };
                        control.ViewModel.AppendLogAction = ShowLog;
                        control.ViewModel.AppendSqlContent = ShowNewWindowLoadFile;
                        panel.Content = control;
                        @group.Items.Add(panel);
                        ActionLayoutPanel(panel, false);
                        control.DataBind(sql);
                    }
                }
            });
        }
        /// <summary>
        /// 显示数据库信息
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="dbname"></param>
        /// <param name="userid"></param>
        private void ShowDBInfo(string ip, string dbname, string userid)
        {
            this.BeginInvokeEx(() =>
                                   {
                                       this.lbIPname.Content = "数据库IP：" + ip;
                                       this.lbDBname.Content = string.Format("数据库名称:{0}", dbname.Replace("_", "__"));
                                       this.lbUserId.Content = "当前用户:" + userid;
                                   });
        }
        /// <summary>
        /// 显示 字段说明信息
        /// </summary>
        /// <param name="caption"></param>
        private void ShowFieldCaption(string caption)
        {
            this.lbFieldName.BeginInvokeEx(() =>
                                               {
                                                   this.lbFieldName.Content = "说明：" + caption;
                                               });
        }
        /// <summary>
        /// 激活 GridViewControl 所在窗体
        /// </summary>
        /// <param name="control"></param>
        private void ShowDataSucess(GridViewControl control)
        {
            LayoutPanel panel = control.Tag as LayoutPanel;
            ActionLayoutPanel(panel,false);
        }

        /// <summary>
        /// 激活指定窗口
        /// </summary>
        /// <param name="item"></param>
        private void ActionLayoutPanel(BaseLayoutItem item,bool isfocus)
        {
            if (item != null)
            {
                if (isfocus)
                {
                    if(!item.IsSelectedItem || !item.IsActive)
                        this.dockManager.LayoutController.Activate(item, true);
                }
                else 
                {
                    if (!item.IsSelectedItem)
                        this.dockManager.LayoutController.Activate(item, false);
                }
            }
        }
        /// <summary>
        /// 查找Document 中存在的控件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        private LayoutPanel GetDocumentControl<T>() where T : DockPanel
        {
            return (from LayoutPanel panel in GetAllLayoutPanel()
                    let control = panel.Content as T
                    where control != null
                    select panel).FirstOrDefault();
        }
        private List<LayoutPanel> GetAllLayoutPanel()
        {
            List<LayoutPanel> list = new List<LayoutPanel>();
            ForeachLayoutItem(this.dockManager.GetItems(),ref list);
            return list;
        }
        private void ForeachLayoutItem(BaseLayoutItem[] collection, ref List<LayoutPanel> list)
        {
            foreach (BaseLayoutItem item in collection)
            {
                LayoutGroup group = item as LayoutGroup;
                if (group != null)
                {
                    ForeachLayoutItem(group.Items.ToArray(), ref list);
                }
                else
                {
                    LayoutPanel panel = item as LayoutPanel;
                    if (panel != null && panel.Caption != null)
                    {
                        if(list.FirstOrDefault(o=>o.Equals(panel)) == null)
                            list.Add(panel);
                    }
                }
            }
        }
        /// <summary>
        /// 获得当前激活的 Document
        /// </summary>
        /// <returns></returns>
        private LayoutPanel GetSelectedDocumentControl<T>() where T:class
        {
            LayoutPanel[] panels = GetAllLayoutPanel().Where(o => o.Content is T).ToArray();
            LayoutPanel p = null;
            foreach (LayoutPanel panel in panels)
            {
                if (panel.IsSelectedItem)
                {
                    if(p == null)
                        p = panel;
                }
                if(panel.Parent == null)
                    this.dockManager.DockController.RemovePanel(panel);
            }
            return p;
        }
       

        /// <summary>
        /// 返回一个闲置的Grid 如果没有 则返回NUll
        /// </summary>
        /// <returns></returns>
        private GridViewControl GetNoBusyGridControl(bool isActive)
        {
            GridViewControl gc = null;

            //记录 闲置的Grid窗体
            List<LayoutPanel> removes = new List<LayoutPanel>();
            foreach (LayoutPanel panel in GetAllLayoutPanel().Where(o => o.Content is GridViewControl).OrderBy(o => o.AllowClose))
            {
                GridViewControl gridcontrol = panel.Content as GridViewControl;
                if (gridcontrol != null)
                {
                    if (!gridcontrol.ViewModel.IsBusy)
                    {
                        if (isActive)
                        {
                            ActionLayoutPanel(panel,false);
                        }
                        if (gc != null)
                        {
                            if (panel.AllowClose)
                            {
                                removes.Add(panel);
                            }
                        }
                        else
                        {
                            gc = gridcontrol;
                        }
                    }
                }
            }
            removes.ForEach(o =>
                {
                    if (o.Parent != null)
                    {
                        o.Parent.Items.Remove(o);
                    }
                });

            return gc;
        }
        /// <summary>
        /// 添加 表定义窗体
        /// </summary>
        /// <param name="entity"></param>
        private void AddTableDefinition(TableEntity entity)
        {
            if (!entity.FileNodes.Any())
            {
                MessageBoxHelper.Show("该表没有列信息.");
                return;
            }
            TableDefinitionControl ctrl = new TableDefinitionControl(entity)
            {
                WriteLog = ShowLog
            };
            ShowNewConrolToDocument(entity.Name, ctrl);
        }

        /// <summary>
        /// 修改 标题 中的修改标识
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="isChange"></param>
        private void SqlControlContentChange(object tag, bool isChange)
        {
            DocumentPanel dp = tag as DocumentPanel;
            if (dp != null)
            {
                if (isChange)
                {
                    bool isNotChange = dp.Caption.ToString().IndexOf('*') < 0;
                    if (isNotChange)
                    {
                        dp.Caption += "*";
                    }
                }
                else
                {
                    dp.Caption = dp.Caption.ToString().Replace("*", "");
                }
            }
        }

        /// <summary>
        /// 获取更新信息
        /// </summary>
        private void UpdateTip()
        {
            Func<string> action = () =>
            {
                System.Reflection.AssemblyName name = System.Reflection.AssemblyName.GetAssemblyName(System.Reflection.Assembly.GetEntryAssembly().Location);

                try
                {
                    if (UpdateHelper.IsDown(name.Version.ToString(), "SQLQuery.exe"))
                    {
                        return "亲，又有新版本了，请记得更新哦。";
                    }
                    return "当前版本:" + name.Version;
                }
                catch
                {
                    return "当前版本:" + name.Version;
                }
            };
            Task<string>.Factory.FromAsync(action.BeginInvoke, action.EndInvoke, null)
                .ContinueWith(t => this.lbUpdateInfo.InvokeEx(() =>
                {
                    this.lbUpdateInfo.Content = t.Result;
                }));
        }
        #endregion

        /// <summary>
        /// 弹出注册窗体
        /// </summary>
        private void ShowRegister(DBEntity entity)
        {
            RegistDB regist = new RegistDB();
            regist.BindData(entity.ConnectionSource);
            if (regist.ShowDialog() == true)
            {
                if (entity.ConnectionSource.ConnectionStr != SysCache.DBConnection.ConnectionStr)
                {
                    TreeViewModel.DeleteCommand.Execute(entity);
                }
                this.TreeViewModel.Connection();
            }
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
           
            ViewModel = new MainViewModel(this.dbtreeview.ViewModel);
            TreeViewModel = this.dbtreeview.ViewModel;
            DataContext = this;

            ViewModel.ShowNewWindowLoadFile = ShowNewWindowLoadFile;
            ViewModel.GetActiveSqlControlPanel = GetSelectedDocumentControl<SQLControl>;
            ViewModel.GetActiveTableDefinitionControlPanel = GetSelectedDocumentControl<TableDefinitionControl>;

            TreeViewModel.AppendSqlAction = ShowSQL;
            TreeViewModel.AppendLogAction = ShowLog;
            TreeViewModel.AppendWindow = (caption, content) => ShowNewWindowLoadFile(caption, content, false);
            TreeViewModel.AppendDBInfo = ShowDBInfo;
            TreeViewModel.AppendFieldCaption = ShowFieldCaption;
            TreeViewModel.AppendSqlContent = ShowNewWindowLoadFile;
            TreeViewModel.ShowTableDefinition = AddTableDefinition;
            TreeViewModel.ShowRegister = ShowRegister;

            this.sqlcontrol.ViewModel.AppendLogAction = ShowLog;
            this.sqlcontrol.ViewModel.AppendDataAction = ShowDS;

            this.gridviewcontrol.ViewModel.AppendLogAction = ShowLog;
            this.gridviewcontrol.AppendDataSucess = ShowDataSucess;
            this.gridviewcontrol.ViewModel.AppendSqlContent = ShowNewWindowLoadFile;
            this.gridviewcontrol.RegistShowAutoFilterAction();

            ComparsionViewModel = new DataComparsionViewModel
                                      {AppendLogAction = ShowLog, ViewInvoke = act => this.InvokeEx(act)};

            //初始化
            this.dbtreeview.Init();
            this.dbtreeview.ViewModel.ShowDescriptionWindows = entity =>
                                                                   {
                                                                       AddDescriptionWindow win = new AddDescriptionWindow(entity);
                                                                       win.ShowDialog();
                                                                   };

            this.sqlcontrol.Init(true);
            this.sqlcontrol.ChangeContentAction = SqlControlContentChange;


            ViewModel.ReadTheme(this);
            this.ribbonControl1.IsMinimized = XmlHelper.Instance.IsRibbonVisible;

           
            if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "\\DockLayout.xml"))
            {
                this.dockManager.RestoreLayoutFromXml(System.AppDomain.CurrentDomain.BaseDirectory + "\\DockLayout.xml");
            }
            if (Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "\\Temporary"))
            {
                foreach (string file in Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory + "\\Temporary", "*.txt"))
                {
                    ShowNewWindowLoadFile(Path.GetFileName(file), File.ReadAllText(file), false);
                }
            }
            if (this.newNote.IsSelectedItem)
            {
                int index = this.documentSQL.Parent.Items.Count - 2;
                this.ActionLayoutPanel(this.documentSQL.Parent.Items[index],true);
            }
            UpdateTip();
        }

    }
}
